﻿using Microsoft.AspNetCore.Mvc.Filters;
using RuYiAdmin.Net.Common.Global;
using RuYiAdmin.Net.Common.Utility;
using RuYiAdmin.Net.Entity.BusinessDTO.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEntity.SystemManagement;
using RuYiAdmin.Net.Entity.BusinessEnum;
using RuYiAdmin.Net.Entity.CoreEntity;
using RuYiAdmin.Net.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.WebApi.AppCode.Filter
{
    /// <summary>
    /// 动作权限过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class PermissionAttribute : ActionFilterAttribute
    {
        private String permission { get; set; }

        public PermissionAttribute(String permission)
        {
            this.permission = permission;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            if (String.IsNullOrEmpty(permission))
            {
                throw new Exception("permission can not be null");
            }

            var token = context.HttpContext.GetToken();

            //获取用户
            var currentUser = RedisUtil.Get<SysUserDTO>(token);

            if (currentUser == null)
            {
                throw new Exception("token is not valid");
            }

            //超级用户放行
            if (currentUser.IsSupperAdmin.Equals((int)YesNo.YES) && currentUser.OrgId.Equals(Guid.Empty))
            {
                return;
            }

            var permissionArray = permission.Split(',');

            #region 获取用户角色

            var listRole = SqlSugarDbContext.Repository.Queryable<SysRoleUser>().Where(t => t.IsDel.Equals(0) && t.UserId.Equals(currentUser.Id)).ToList();
            var roleIds = listRole.Select(t => t.RoleId).ToArray();

            #endregion

            #region  获取角色菜单

            var listRoleMenu = new List<SysRoleMenu>();
            foreach (var item in roleIds)
            {
                var roleMenus = SqlSugarDbContext.Repository.Queryable<SysRoleMenu>().Where(t => t.IsDel.Equals(0) && t.RoleId.Equals(item)).ToList();
                listRoleMenu.AddRange(roleMenus);
            }

            var menuIds = listRoleMenu.Select(t => t.MenuId).ToArray();

            #endregion

            #region 获取菜单

            var listMenus = SqlSugarDbContext.Repository.Queryable<SysMenu>().
                                                         Where(t => t.IsDel.Equals(0) && t.MenuType.Equals(MenuType.Button) || t.MenuType.Equals(MenuType.View)).
                                                         ToList();

            #endregion

            #region 权限判断

            var result = false;

            foreach (var item in menuIds)
            {
                var menu = listMenus.Where(t => t.Id.Equals(item)).FirstOrDefault();

                if (menu != null && !String.IsNullOrEmpty(menu.Code))
                {
                    //是否包含权限组
                    if (permissionArray.Contains(menu.Code))
                    {
                        result = true;
                        break;
                    }
                }
            }

            #endregion

            if (!result)
            {
                throw new Exception("access denied");
            }
        }
    }
}
